<style lang="less">
    @import "./roleManage.less";
</style>
<template>
    <div class="search">
        <Row>
            <Col>
            <Card>
                <Row class="operation">
                    <Button @click="addRole" type="primary" icon="plus-round">添加角色</Button>
                    <Button @click="refresh" type="success" icon="refresh">刷新</Button>
                </Row>
                <Row>
                    <Alert show-icon>
                        已选择 <span class="select-count">{{selectCount}}</span> 项
                        <a class="select-clear" @click="clearSelectAll">清空</a>
                    </Alert>
                </Row>
                <Row>
                    <Table :loading="loading" border
                           :columns="columns" :data="data"
                           ref="table" sortable="custom"
                           @on-selection-change="showSelect"></Table>
                </Row>
                <Row type="flex" justify="end" class="page">
                  <Page
                    :current="pageNumber"
                    :total="total"
                    :page-size="pageSize"
                    @on-change="changePage"
                    @on-page-size-change="changePageSize"
                    :page-size-opts="[10,20,50]"
                    size="small"
                    show-total
                    show-elevator
                    show-sizer
                  ></Page>
                </Row>
            </Card>
            </Col>
        </Row>
        <Modal :title="modalTitle" v-model="roleModalVisible" :mask-closable='false' :width="500">
            <Form ref="roleForm" :model="roleForm" :label-width="80" :rules="roleFormValidate">
                <FormItem label="角色名称" prop="name">
                    <Input v-model="roleForm.name" placeholder="按照Spring Security约定建议以‘ROLE_’开头"/>
                </FormItem>
                <FormItem label="备注" prop="description">
                    <Input v-model="roleForm.description"/>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="cancelRole">取消</Button>
                <Button type="primary" :loading="submitLoading" @click="submitRole">提交</Button>
            </div>
        </Modal>
        <Modal :title="permTitle" v-model="permModalVisible" :mask-closable='false' :width="500"
               :styles="{top: '30px'}">
            <Tree ref="tree" :data="permData" multiple></Tree>
            <Spin size="large" v-if="treeLoading"></Spin>
            <div slot="footer">
                <Button type="text" @click="cancelPermEdit">取消</Button>
                <Button @click="selectTreeAll">全选/反选</Button>
                <Button type="primary" :loading="submitPermLoading" @click="submitPermEdit">提交</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
  import Cookies from 'js-cookie';
  import { 
    getAllRoles, 
    getAllPermission, 
    updateRole, 
    insertRole, 
    getRolePermissionIds, 
    updateRolePermissionByRoleId, 
    setPermissions,
    insertPermisssion
  } from '@/api/permission';
  import moment from 'moment';
  import util from '@/libs/util';
  export default {
    name: "role-manage",
    data() {
      return {
        userId: parseInt(JSON.parse(Cookies.get('userInfo')).id),
        loading: true,
        modalType: 0,
        roleModalVisible: false,
        permModalVisible: false,
        modalTitle: '',
        permTitle: '',
        roleForm: {
          id: 0,
          name: '',
          description: ''
        },
        roleFormValidate: {
          name: [{required: true, message: "角色名称不能为空", trigger: "blur"}]
        },
        submitLoading: false,
        submitPermLoading: false,
        treeLoading: false,
        selectList: [],
        selectCount: 0,
        columns: [
          {
            type: "selection",
            width: 60,
            align: "center"
          },
          {
            type: "index",
            width: 60,
            align: "center"
          },
          {
            title: "角色名称",
            key: "name",
            width: 200,
          },
          {
            title: "备注",
            key: "description",
            width: 260,
          },
          {
            title: "创建人",
            key: "real_name",
            align: "center",
            width: 110,
          },
          {
            title: "创建时间",
            key: "add_time",
            align: "center",
            width: 160,
            render: (h, params) => {
              let re = moment(params.row.add_time).format('YYYY-MM-DD');
              return h("div", re);
            }
          },
          {
            title: "状态",
            key: "is_delete",
            align: "center",
            width: 90,
            render: (h, params) => {
              let re = "";
              if (params.row.is_delete === 1) {
                re = "删除";
              } else if (params.row.is_delete === 0) {
                re = "正常";
              }
              return h("div", re);
            }
          },
          {
          title: "操作",
          key: "action",
          align: "center",
          fixed: "right",
          width: 300,
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.editPerm(params.row);
                    }
                  }
                },
                "菜单权限"
              ),
              
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.row);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row);
                    }
                  }
                },
                params.row.is_delete === 0 ? "删除" : "恢复"
              )
            ]);
          }
        }
        ],
        data: [],
        pageNumber: 1,
        pageSize: 10,
        total: 0,
        permData: [],
        editRolePermId: "",
        selectPermList: [],
        selectAllFlag: false
      }
    },
    created() {
      this.getRoles();
    },
    methods: {
      // 分页获取角色
      getRoles() {
        this.loading = true;
        getAllRoles({pageNumber: this.pageNumber,pageSize: this.pageSize}).then(res => {
          this.total = res.data.count;
          if (this.total > 0) {
            let params = {};
            params.page = (this.pageNumber - 1 < 0 ? 0 : this.pageNumber - 1) * this.pageSize;
            params.limit = this.pageSize;
            this.data = res.data.raws;
            this.loading = false;
          }
        });
      },
      addRole() {
        const hasPermission = util.oneOf('add', this.$route.meta.permTypes);
        if (!hasPermission) {
          this.$Message.error('抱歉，您没有操作权限！');
          return;
        };
        this.modalType = 0;
        this.modalTitle = '添加角色';
        this.roleModalVisible = true;
      },
      edit(v) {
        const hasPermission = util.oneOf('edit', this.$route.meta.permTypes);
        if (!hasPermission) {
          this.$Message.error('抱歉，您没有操作权限！');
          return;
        };
        this.modalType = 1;
        this.roleForm.id = v.id;
        this.roleForm.name = v.name;
        this.roleForm.description = v.description;
        this.modalTitle = '编辑角色';
        this.roleModalVisible = true;
      },
      remove(v) {
        const hasPermission = util.oneOf('delete', this.$route.meta.permTypes);
        if (!hasPermission) {
          this.$Message.error('抱歉，您没有操作权限！');
          return;
        };
        let msg = v.is_delete === 0 ? '删除' : '恢复';
        this.$Modal.confirm({
          title: "确认"+msg,
          content: "您确认要" + msg + "角色 " + v.name + " ?",
          onOk: () => {
            let params = {};
            params.id = v.id;
            params.name = v.name;
            params.description = v.description;
            if (v.is_delete === 0) {
              params.is_delete = 1;
              updateRole(params).then(res => {
                this.refresh();
              });
            } else {
              params.is_delete = 0;
              updateRole(params).then(res => {
                this.refresh();
              });
            }
          }
        });
      },
      editPerm(v) {
        const hasPermission = util.oneOf('editPerm', this.$route.meta.permTypes);
        if (!hasPermission) {
          this.$Message.error('抱歉，您没有操作权限！');
          return;
        };
        this.editRolePermId = v.id;
        getAllPermission().then(res => {
          this.permData = res.data;
          //获取role_id的权限
          getRolePermissionIds({role_id: v.id}).then(res => {
            if (res.code === 0) {
              let rolePerms = res.data;
              this.checkPermTree(this.permData, rolePerms);
              this.permTitle = '分配'+v.name+'角色权限(点击选择)';
              this.permModalVisible = true;
            }
          })
        });
      },
      // 递归判断子节点
      checkPermTree(permData, rolePerms) {
        let that = this;
        permData.forEach(function(p) {
          if (that.hasPerm(p, rolePerms)) {
            p.selected = true;
          } else {
            p.selected = false;
          }
          if (p.children && p.children.length > 0) {
            that.checkPermTree(p.children, rolePerms);
          }
        });
      },
      // 判断角色拥有的权限节点勾选
      hasPerm(p, rolePerms) {
        let flag = false;
        for (let i = 0; i < rolePerms.length; i++) {
          if (p.id === rolePerms[i].id) {
            flag = true;
            break;
          }
        }
        if (flag) {
          return true;
        }
        return false;
      },
      // 全选反选
      selectTreeAll() {
        this.selectAllFlag = !this.selectAllFlag;
        let select = this.selectAllFlag;
        this.selectedTreeAll(this.permData, select);
      },
      // 递归全选节点
      selectedTreeAll(permData, select) {
        let that = this;
        permData.forEach(function(e) {
          e.selected = select;
          if (e.children && e.children.length > 0) {
            that.selectedTreeAll(e.children, select);
          }
        });
      },
      refresh() {
        this.getRoles();
      },
      clearSelectAll() {
        this.$refs.table.selectAll(false);
      },
      changeSelect() {
      },
      changePage(v) {
        this.pageNumber = v;
        this.getRoles();
        this.clearSelectAll();
      },
      changePageSize(v) {
        this.pageSize = v;
        this.getRoles();
        this.clearSelectAll();
      },
      showSelect(e) {
        this.exportData = e;
        this.selectList = e;
        this.selectCount = e.length;
      },
      cancelRole() {
        this.$refs.roleForm.resetFields();
        this.roleModalVisible = false;
      },
      submitRole() {
        this.$refs.roleForm.validate(valid => {
          if (valid) {
            if (this.roleForm.name.substr(0, 5) !== 'ROLE_') {
              this.$Message.error('角色名称必须以“ROLE_”开始');
              return false;
            }
            let params = {};
            params.name = this.roleForm.name;
            params.description = this.roleForm.description;
            if (this.modalType === 0) {     //新增角色
              params.add_user = this.userId;
              insertRole(params).then(res => {
                this.$Message.success(res.message);
                this.refresh();
              });
            } else {                        //编辑角色
              params.id = this.roleForm.id;
              updateRole(params).then(res => {
                this.$Message.success(res.message);
                this.refresh();
              });
            }
            this.$refs.roleForm.resetFields();
            this.roleModalVisible = false;
          }
        });
      },
      cancelPermEdit() {
        this.permModalVisible = false;
      },
      submitPermEdit() {
        this.submitPermLoading = true;
        let permIds = '';
        let selectedNodes = this.$refs.tree.getSelectedNodes();
        selectedNodes.forEach(function(e) {
          permIds += e.id + ',';
        });
        permIds = permIds.substring(0, permIds.length - 1);
        if (permIds === '') {
          //清除所有权限
          let params = {
            role_id: this.editRolePermId,
            is_delete: 1
          }
          updateRolePermissionByRoleId(params).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
            }
            this.submitPermLoading = false;
            this.permModalVisible = false;
            return false;
          });
        } else {
          let permIdsArray = [];
          permIds.split(',').forEach(e => {
            permIdsArray.push(parseInt(e));
          });
          let params = {};
          params.role_id = this.editRolePermId;
          params.permIds = permIds;
          setPermissions(params).then(res => {
            let hasPermIds = [];
            res.data.forEach(e => {
              hasPermIds.push(e.permission_id);
            });
            for (let i = 0; i < hasPermIds.length; i++) {
              for (let j = 0; j < permIdsArray.length; j++) {
                if (permIdsArray[j] == hasPermIds[i]) {
                  permIdsArray.splice(j, 1);
                  j--;
                }
              }
            }
            let params = {};
            params.role_id = this.editRolePermId;
            permIdsArray.forEach(item =>{
              setTimeout(() => {
                params.permission_id = item;
                insertPermisssion(params).then(res => {
                });
              },200);

            });
          });
          this.$Message.success('设置完成');
          this.submitPermLoading = false;
          this.permModalVisible = false;
        }
      },
    },
  }
</script>
